package com.qywx.task;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qywx.dao.DataSourceUserDao;
import com.qywx.dao.DepartmentDao;
import com.qywx.dao.TagRuleDao;
import com.qywx.dao.UserDao;
import com.qywx.entity.DataSourceUserEntity;
import com.qywx.entity.DepartmentEntity;
import com.qywx.entity.UserEntity;
import com.qywx.service.impl.DepartmentServiceImpl;
import com.qywx.service.impl.TagServiceImpl;
import com.qywx.service.impl.UserServiceImpl;
import com.qywx.utils.RestTemplateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@EnableScheduling
public class ScheduleGetUser {
    private final static Logger log = LoggerFactory.getLogger(DepartmentServiceImpl.class);
    @Autowired
    private DataSourceUserDao dataSourceUserDao;
    @Autowired
    private DepartmentDao departmentDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private RestTemplateUtil restTemplateUtil;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private TagRuleDao tagRuleDao;
    @Autowired
    private TagServiceImpl tagService;

    @Scheduled(cron = "0 30 16 1/1 * ?")
    //@Scheduled(cron = "0 5/10 * * * ?")
    public void getDataSourceUser() {
        QueryWrapper<DataSourceUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_synchronize","1");
        List<DataSourceUserEntity> list = dataSourceUserDao.selectList(queryWrapper);
        log.info("一共获取了" + list.size() + "条源数据");
        int sum = 0;
        for (int i = 0; i < list.size(); i++) {
            log.info("开始插入第" + (i + 1) + "条源数据");
            DataSourceUserEntity dataSourceUserEntity = list.get(i);
            //将微信id赋值给userid
            dataSourceUserEntity.setUserid(dataSourceUserEntity.getWXId());
            UserEntity user = userDao.selectById(dataSourceUserEntity.getUserid());
            //判断用户是否已经存在
            if (user == null) {
                saveUser(dataSourceUserEntity);
            } else {
                //已存在删除再保存
                userDao.deleteById(dataSourceUserEntity.getUserid());
                //删除部门关系
                userDao.deleteDepUser(dataSourceUserEntity.getUserid());
                //删除标签关系
                userDao.delUserTad(dataSourceUserEntity.getUserid());
                saveUser(dataSourceUserEntity);
            }
            log.info("第" + (i + 1) + "条源数据插入成功");
            sum++;
        }
        log.info("一共插入" + sum + "条数据");

    }

    private void saveUser(DataSourceUserEntity dataSourceUserEntity) {
        //不存在
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(dataSourceUserEntity, userEntity);
        userEntity.setUsertype(dataSourceUserEntity.getUserType());
        //判断是内部人员还是外部人员
        String usertype = userEntity.getUsertype();
        if ("1".equals(usertype)) {
            //将部门名称转换成对应的部门id
            String departments = userEntity.getDepartment();
            String[] split = departments.split(",");
            StringBuffer stringBuffer = new StringBuffer();
            for (int j = 0; j < split.length; j++) {
                List<DepartmentEntity> departmentEntityList = departmentDao.findByNameAll(split[j]);
                if(departmentEntityList.size()>0){
                    DepartmentEntity departmentEntity = departmentEntityList.get(0);
                    if (departmentEntity != null) {
                        stringBuffer.append(departmentEntity.getId()).append(",");
                    }
                }else {
                    continue;
                }
            }
            String department = stringBuffer.toString();
            userEntity.setDepartment(department);
            //保存人员
            userDao.insert(userEntity);
            dataSourceUserDao.updateIsSync(userEntity.getUserid());
            //保存人员部门关系表
            userService.saveDepartUser(department, userEntity.getUserid());
            //保存微信端
            String accessToken = restTemplateUtil.getaccessToken();
            String getUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken + "&userid=" + dataSourceUserEntity.getUserid();
            Map resultMap = restTemplate.getForObject(getUrl, Map.class);
            Integer code = (Integer) resultMap.get("errcode");
            if (0 != code) {
                //不存在，保存到微信端
                userService.saveToWechat(userEntity);
            } else {
                //存在进行更新
                updateWechatNoMobile(userEntity);
            }
            //保存人员标签关系表(待定)：根据属性一到十来查询标签id
            List<Long> tagIds = tagRuleDao.selectByAttribute1(userEntity);
            for (int i = 0; i < tagIds.size(); i++) {
                tagService.saveTagUser(tagIds.get(i), userEntity.getUserid());
            }
        } else {
            userDao.insert(userEntity);
        }
    }

    private void updateWechatNoMobile(UserEntity userEntity) {
        JSONObject jsonObj = (JSONObject) JSONObject.toJSON(userEntity);
        List<Long> depList = new ArrayList<>();
        List<String> depId = userDao.findDepartmentId(userEntity.getUserid());
        for (int i = 0; i < depId.size(); i++) {
            String s = depId.get(i);
            if (!"".equals(s)) {
                depList.add(Long.parseLong(s));
            }
        }
        jsonObj.put("department", depList);
        //英文名填工号
        Map mapxEtended = new HashMap();
        mapxEtended.put("工号",userEntity.getUserNumber());
        mapxEtended.put("科室",userEntity.getDepartmentOffice());
        mapxEtended.put("科室代码",userEntity.getOfficeNumber());
        JSONObject jsonObject = splicingExtendedFields(mapxEtended);
        jsonObj.put("extattr",jsonObject);
        jsonObj.remove("mobile");
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        //请求体
        HttpEntity<String> formEntity = new HttpEntity<String>(jsonObj.toString(), headers);
        String accessToken = restTemplateUtil.getaccessToken();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token=" + accessToken;
        Map resultMap = restTemplate.postForObject(url, formEntity, Map.class);
        String errmsg = (String) resultMap.get("errmsg");
        log.info("===========保存用户标签到微信返回信息===========" + errmsg, errmsg);
        Integer code = (Integer) resultMap.get("errcode");
        if (0 == code) {
            userEntity.setIsSynchronize("1");
            userEntity.setStat(1);
            userDao.updateById(userEntity);
        } else {
            userEntity.setIsSynchronize("2");
            userEntity.setStat(1);
            userDao.updateById(userEntity);
        }
    }

    public JSONObject splicingExtendedFields(Map map) {
        //扩展字段
        JSONObject jsonObject2 = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        for(Object key : map.keySet()){
            //json数组
            JSONObject jsonObject3 = new JSONObject();
            jsonObject3.put("type",0);
            jsonObject3.put("name",key);
            JSONObject jsonObject4 = new JSONObject();
            jsonObject3.put("text",jsonObject4);
            jsonObject4.put("value",map.get(key));
            jsonArray.add(jsonObject3);
        }
        jsonObject2.put("attrs",jsonArray);
        return jsonObject2;
    }
}
